﻿#include "jsonhelp.h"
#include <QApplication>
#include <QDir>
#include <QStandardPaths>

#include <QDateTime>
#include <QDebug>

#include <QFile>
//#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonParseError>

#include <QHBoxLayout>
#include <QTabWidget>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QHeaderView>
#include <QLabel>
jsonHelp::jsonHelp(QObject *parent) :
    QObject(parent)
{
    m_recordDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator() + "record" + QDir::separator();
    QDir dir(m_recordDir);
    if(!dir.exists())
        dir.mkpath(m_recordDir);
    m_recordFile = m_recordDir + QString("%1.dat").arg(QDateTime::currentDateTime().toString("yyyyMMdd"));

    //todo delete
    //test
//    insertData();
}

bool jsonHelp::insertData()
{
    bool ok = false;
    if(!QFile::exists(m_recordFile))
    {
        QJsonObject jsonmain;
        jsonmain.insert("appname", QApplication::applicationName());
        jsonmain.insert("datetime", QDateTime::currentDateTime().toString());
        jsonmain.insert("version", 5);//QApplication.version
        jsonmain.insert("author", "vacant");

        QJsonArray jsongroup;//分组
        for(int k = 0;k<2;k++)
        {//group
            QJsonObject jsongroup_sub;//分组
            QString str_groupName = QStringLiteral("组号:")+QString::number(1+k);
            jsongroup_sub.insert("name",str_groupName);// 参数
            jsongroup_sub.insert("ip","192.168.1.120");
            QJsonArray jsonplane;//该组对应餐数所投值-for
            {
                for(int j = 0;j<4;j++)
                {//模拟4餐
                    //! [test]
                    QJsonObject jsoneach;//第?餐对应数据
                    {
                        QString str_eacheName = QStringLiteral("第")+QString::number(j+1)+QStringLiteral("餐投喂标准");
                        {
                            jsoneach.insert("name",str_eacheName);//餐数名称
                            jsoneach.insert("puttime",QDateTime::currentDateTime().toString());//投放时对应时间

                            QJsonArray jsarraybox;
                            QJsonObject jsobjweigh;
                            QJsonObject jsobjput;

                            int count = 24;
                            qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
                            for(int i = 0;i<24;i++)
                            {
                                jsarraybox.append(QString::number(count--));
//                                jsobjweigh.insert(QString::number(i+1),QString::number(i+qrand()%20*0.1));
//                                jsobjput.insert(QString::number(i+1),QString::number(i+qrand()%20*0.1));
                                jsobjweigh.insert(QString::number(i+1),QString::number(0));
                                jsobjput.insert(QString::number(i+1),QString::number(0));
                            }
                            jsoneach.insert("boxnum",jsarraybox);//箱号顺序
                            jsoneach.insert("weigh",jsobjweigh);//对应箱号-称量值
                            jsoneach.insert("putvalue",jsobjput);//对应箱号-抽喂值
                        }
                    }
                    jsonplane.append(jsoneach);//数组形式插入
                    //! [end]
//                    jsonplane.append(m_putEach);//数组形式插入
                }
            }
            jsongroup_sub.insert(str_groupName,jsonplane);
            jsongroup.append(jsongroup_sub);
        }
        jsonmain.insert("value",jsongroup);
        QJsonDocument document;
        document.setObject(jsonmain);

        //    doc.toBinaryData();
        QFile file(m_recordFile);
        file.fileName();
        if(file.open(QIODevice::WriteOnly)){
            qDebug("fileOpen success.");
            file.write(document.toJson());
            ok = true;
        }else
            qDebug("fileOpen not success.");
    }
    //    else{
    //        //update file.
    //        QByteArray data;
    //        QFile file(m_recordFile);
    //        file.fileName();
    //        if(file.open(QIODevice::ReadOnly)){
    //            qDebug("fileOpen success.");
    //            data = file.readAll();
    //            parseData(data);
    //            ok = true;
    //        }else
    //            qDebug("fileOpen not success.");
    //    }
    return ok;

}

QJsonArray jsonHelp::insertGroup(QString groupName, QString ipadd)
{
    qDebug()<<endl<<"check the m_putEach:"<<m_putEach<<endl<<endl;
    bool ok = false;
    QJsonArray jsongroup = parseGroup(groupName,ok);//分组
    if(!ok)//未存在时,该组下所有数据直接插入
    {//group
        QJsonObject jsongroup_sub;//分组
        jsongroup_sub.insert("name",groupName);// 参数
        jsongroup_sub.insert("ip",ipadd);
        QJsonArray jsonplane ;//该组对应餐数所投值-for

        jsonplane.append(m_putEach);//数组形式插入

        jsongroup_sub.insert(groupName,jsonplane);
        jsongroup.append(jsongroup_sub);
    }//否则进行判断后再插入
    else{
        QJsonObject jsongroup_sub;
        int indexgroup = -1;
        for(int ig = 0;ig<jsongroup.size();ig++){
            QJsonValue jsvalue = jsongroup.at(ig);
            if(jsvalue.toObject().value("name")==groupName){
                indexgroup = ig;
                break;
            }
        }
        if(indexgroup != -1){//找到对应组号index.
            jsongroup_sub = jsongroup.at(indexgroup).toObject();
//            jsongroup_sub.insert("name",groupName);
//            jsongroup_sub.insert("ip",ipadd);
            QJsonArray jsonplane = jsongroup_sub.value(groupName).toArray();//该组对应餐数所投值-for
            bool isReplace = false;
            for(int i = 0;i<jsonplane.size();i++){
                int index = -1;
                foreach(QJsonValue jsvalue_sub,jsonplane){
                    if(jsvalue_sub.toObject().value("name") == m_putEach.value("name")){
                        index = i;
                        break;
                    }
                }
                if(index != -1){
                    jsonplane.replace(index,m_putEach);
                    isReplace = true;
                    break;
                }
            }
            if(!isReplace)
            {
                jsonplane.append(m_putEach);//not this
            }
            QJsonObject jsgroup_single;
            jsgroup_single.insert(groupName,jsonplane);
            jsgroup_single.insert("name",groupName);
            jsgroup_single.insert("ip",ipadd);
            jsongroup.replace(indexgroup,jsgroup_single);
        }
    }
    m_pugGroup = jsongroup;

    //remove to insertData()
    QJsonObject jsonmain;
    jsonmain.insert("appname", QApplication::applicationName());
    jsonmain.insert("datetime", QDateTime::currentDateTime().toString());
    jsonmain.insert("version", 5);
    jsonmain.insert("author", "vacant");

    jsonmain.insert("value",jsongroup);
    QJsonDocument document;
    document.setObject(jsonmain);

    QFile file(m_recordFile);
    file.fileName();
    if(file.open(QIODevice::WriteOnly)){
        qDebug("fileOpen success.");
        file.write(document.toJson());
        file.close();
    }
    return jsongroup;
}

QJsonObject jsonHelp::insertEach(QString tbname,QStringList strBoxnum,QHash<QString, QString> m_mapvalue, QMap<QString, QString> m_mapPutvalue)
{//single one.
    QJsonObject jsoneach;//第?餐对应数据
//    QString str_eacheName = QStringLiteral("第")+QString::number(j+1)+QStringLiteral("餐投喂标准");
    {
        jsoneach.insert("name",tbname);//餐数名称
        jsoneach.insert("puttime",QDateTime::currentDateTime().toString());//投放时对应时间

        QJsonArray jsarraybox;
        QJsonObject jsobjweigh;
        QJsonObject jsobjput;

        foreach(QString str,strBoxnum)
            jsarraybox.append(str);

        QHashIterator<QString,QString> itor_boxvalue(m_mapvalue);
        while(itor_boxvalue.hasNext()){
            itor_boxvalue.next();
            jsobjweigh.insert(itor_boxvalue.key(),itor_boxvalue.value());
        }
        QMapIterator<QString,QString> itor_realvalue(m_mapPutvalue);
        while(itor_realvalue.hasNext()){
            itor_realvalue.next();
            jsobjput.insert(itor_realvalue.key(),itor_realvalue.value());
        }
        jsoneach.insert("boxnum",jsarraybox);//箱号顺序
        jsoneach.insert("weigh",jsobjweigh);//对应箱号-称量值
        jsoneach.insert("putvalue",jsobjput);//对应箱号-抽喂值
    }
    m_putEach = jsoneach;
    return jsoneach;
}

QJsonObject jsonHelp::insertEach(QString tbname, QStringList strBoxnum, QMap<QString, QString> m_mapvalue, QMap<QString, QString> m_mapPutvalue)
{
    //map to hash
    QHash<QString,QString> hash;
    QMapIterator<QString, QString> itor(m_mapvalue);
    while(itor.hasNext()){
        if(itor.next()==m_mapvalue.end())
            continue;
        hash.insert(itor.key(),itor.value());
    }

    return insertEach(tbname,strBoxnum,hash,m_mapPutvalue);
}



QJsonObject jsonHelp::parseMain(QByteArray byte_array,QJsonParseError *json_error)
{
    QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array, json_error);
    QJsonObject obj;
    if(json_error->error == QJsonParseError::NoError)
    {
        if(parse_doucment.isObject())
        {
            obj = parse_doucment.object();
        }
    }
    return obj;
}

void jsonHelp::parseData(QByteArray byte_array)
{
    //parse-解析
    {
        QJsonParseError json_error;
        QJsonObject obj = parseMain(byte_array,&json_error);

        qDebug()<<"json_error:"<<json_error.errorString();

        if(json_error.error == QJsonParseError::NoError){
            if(obj.contains("datetime"))
            {
                QJsonValue version_value = obj.take("datetime");
                if(version_value.isString())
                {
                    QString datatime = version_value.toVariant().toString();
                    qDebug()<<"datetime:"<<datatime;
                }
            }
            if(obj.contains("author"))
            {
                QJsonValue version_value = obj.take("author");
                if(version_value.isString())
                {
                    QString author = version_value.toString();
                    qDebug()<<"author:"<<author;
                }
            }
            if(obj.contains("value"))
            {
                foreach(QJsonValue value_group,obj.value("value").toArray())
                {
                    //insert.
                    //! [1]
                    bool isExist = false;
                    QVariantList list = obj.value("value").toArray().toVariantList();
                    //check out the value exist.
                    foreach(QVariant var ,list)
                    {
                        QRegExp reg("[\\d]{1,}");
                        if(var.toString().contains(reg)){
//                            isExist = true;
                            int index = list.indexOf(var);
                            obj.value("value").toArray().replace(index,QJsonValue());
                            break;
                        }
                    }
                    //! [1]
                    QJsonObject obj_group = value_group.toObject();
                    QJsonValue _value = obj_group.take("ip");
                    if(_value.isString())
                    {
                        QString ipvalue = _value.toString();
                        qDebug()<<"ip:"<<ipvalue;
                    }
                    _value = obj_group.take("name");
                    if(_value.isString())
                    {
                        QString group_name = _value.toString();
                        qDebug()<<"name:"<<group_name;
//                        if(group_name)
                        //parse group data.
                        if(obj_group.contains("value"))
                        {
                            QJsonArray objarray_plane = obj_group.value("value").toArray();
                            if(!objarray_plane.isEmpty()){
                                int size_count = objarray_plane.size();
                                for(int j = 0;j<size_count;j++){
                                    QJsonValue value_plane = objarray_plane.at(j);
                                    if(value_plane.isObject()){
                                        QJsonObject value_plane_each = value_plane.toObject();
                                        if(value_plane_each.contains("boxnum")){
                                            qDebug()<<"boxnum";//<<value_plane_each.value("boxnum").toArray();
                                        }
                                        if(value_plane_each.contains("name")){
                                            qDebug()<<"name:"<<value_plane_each.value("name").toString();
                                        }
                                        if(value_plane_each.contains("puttime")){
                                            qDebug()<<"puttime:"<<value_plane_each.value("puttime").toString();
                                        }
                                        if(value_plane_each.contains("putvalue")){
                                            qDebug()<<"putvalue:";//<<value_plane_each.value("putvalue").toObject();
                                        }
                                        if(value_plane_each.contains("weigh")){
                                            qDebug()<<"weigh:";//<<value_plane_each.value("weigh").toObject();
                                        }
                                        qDebug()<<"value:"<<j;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

QJsonArray jsonHelp::parseGroup(QString groupname ,bool &isExist)
{
    QJsonArray JsgroupArray;

    isExist = readData(QDateTime::currentDateTime());
    if(!isExist)//if suceess the " mainobj " value will be get.
        return JsgroupArray;

    if(!mainobj.isEmpty()){
        QJsonObject obj = mainobj;
        QJsonParseError json_error = m_parseerror;

        if(json_error.error == QJsonParseError::NoError){
            if(obj.contains("value"))
            {
                JsgroupArray = obj.value("value").toArray();
                foreach(QJsonValue value_group,JsgroupArray)//组
                {
                    QJsonObject obj_group = value_group.toObject();

                    QJsonValue _value = obj_group.take("name");
                    if(_value.isString())
                    {
                        if(groupname == _value.toString()){
                            isExist = true;
                            break;
                        }
                    }
                }
            }
        }
    }
    return JsgroupArray;
}

void jsonHelp::parseEach()
{

}

void jsonHelp::paraseGroupForTab(QJsonObject obj, QTabWidget *tabWidgetIn, int index)
{
    foreach(QJsonValue value_group,obj.value("value").toArray())//组
    {
        QJsonObject obj_group = value_group.toObject();
        QJsonValue _value;// = obj_group.take("ip");

//        qDebug()<<obj<<endl<<endl<<obj_group<<endl<<endl;
        _value = obj_group.take("name");
        QString group_name = "new";
        if(_value.isString())
        {
            group_name = _value.toString();
        }
//qDebug()<<endl<<"paraseGroupForTab----:"<<group_name<<tabWidgetIn->tabToolTip(index)<<index<<tabWidgetIn->currentIndex()<<endl<<endl;

//        if(group_name == tabWidgetIn->tabToolTip(tabWidgetIn->currentIndex()))
        if(group_name == (tabWidgetIn->tabToolTip(index)))
        {
            QWidget *widgetGroup = tabWidgetIn->currentWidget();
            QTableWidget *table = new QTableWidget(widgetGroup);
            QVBoxLayout *grouphlayout = new QVBoxLayout;
            QHBoxLayout *toplayout = new QHBoxLayout;
            grouphlayout->setMargin(10);
            grouphlayout->setSpacing(6);
            toplayout->setMargin(5);
            toplayout->setSpacing(6);

            grouphlayout->addLayout(toplayout);
            grouphlayout->addWidget(table);

            widgetGroup->setObjectName("widgetGroup"+_value.toString());
            widgetGroup->setStyleSheet(QString("QWidget#%1{background:transparent;}").arg(widgetGroup->objectName()));

            connect(table,&QTableWidget::cellChanged,[=](int /*row*/, int column){
                //                                if(table->item(row,column)->text().contains(QStringLiteral("投放时间")))
                if(column == 0 )
                    return;
                table->resizeColumnToContents(column);
            });

            _value = obj_group.take("ip");
            if(_value.isString())
            {
                QString ipvalue = _value.toString();

                if(!group_name.isEmpty()){
//                    toplayout->addWidget(new QLabel(QStringLiteral("组号：")));
                    toplayout->addWidget(new QLabel(group_name));
                    toplayout->addSpacerItem(new QSpacerItem(5,2,QSizePolicy::Expanding,QSizePolicy::Fixed));
                }
                toplayout->addWidget(new QLabel(QStringLiteral("IP地址：")));
                toplayout->addWidget(new QLabel(ipvalue));
                toplayout->addSpacerItem(new QSpacerItem(5,2,QSizePolicy::Expanding,QSizePolicy::Fixed));
            }

            widgetGroup->setLayout(grouphlayout);//group main widet set layout.
            //end here of group top widget.

            //parse group data.
            if(obj_group.contains(group_name))
            {
                QJsonArray objarray_plane = obj_group.value(group_name).toArray();
                if(!objarray_plane.isEmpty()){
                    int size_count = objarray_plane.size();
                    for(int j = 0;j<size_count;j++){//餐数
                        QJsonValue value_plane = objarray_plane.at(j);
                        if(value_plane.isObject()){
                            table->setColumnCount(24);//列数规定24列

                            int insertrow = table->rowCount();
                            if(insertrow==0){
                                table->insertRow(insertrow);//第一行
                                insertrow = 1;
                            }
                            else
                                table->insertRow(insertrow);//第一行

                            QJsonObject value_plane_each = value_plane.toObject();
                            if(value_plane_each.contains("puttime")){
                                QTableWidgetItem *item_each = new QTableWidgetItem;
                                item_each->setText(QStringLiteral("投放时间：")+value_plane_each.value("puttime").toString());
                                table->setItem(insertrow==1?0:insertrow,0,item_each);
                                table->setSpan(table->rowCount()-1,0,1,24);
                            }

                            if(value_plane_each.contains("name")){//水平列对应名称
                                //                                                listverheader.append(value_plane_each.value("name").toString());
                                if(!table->verticalHeaderItem(table->verticalHeader()->count()-1)){
                                    QTableWidgetItem *verItem = new QTableWidgetItem;
                                    verItem->setText(value_plane_each.value("name").toString());
                                    table->setVerticalHeaderItem(table->rowCount()-1,verItem);
                                }else{
                                    QTableWidgetItem *verItem = table->verticalHeaderItem(table->verticalHeader()->count()-1);
                                    if(verItem)
                                        verItem->setText(value_plane_each.value("name").toString());
                                }

                            }
                            //                                            table->setVerticalHeaderLabels(listverheader);

                            QStringList list_boxnum;
                            if(value_plane_each.contains("boxnum")){
                                table->insertRow(table->rowCount());//新插入一行用于存放箱号
                                for(int i = 0;i<value_plane_each.value("boxnum").toArray().count();i++)
                                {
                                    QString var = value_plane_each.value("boxnum").toArray().at(i).toString();//.toVariantList().at(i);
                                    QTableWidgetItem *item_boxnum = new QTableWidgetItem;
                                    item_boxnum->setText(var);
                                    list_boxnum.append(var);
                                    table->setItem(table->rowCount()-1,i,item_boxnum);
                                    //                                                    map_value.insert(var,"");//the default value
                                    //                                                    map_realevalue.insert(var,"");
                                }
                                //                                                table->verticalHeaderItem(table->rowCount()-1)->setText(QStringLiteral("箱号"));//位于table insertrow之后
                                if(!table->verticalHeaderItem(table->verticalHeader()->count()-1)){
                                    QTableWidgetItem *verItem = new QTableWidgetItem;
                                    verItem->setText(QStringLiteral("箱号"));
                                    table->setVerticalHeaderItem(table->rowCount()-1,verItem);
                                }else{
                                    QTableWidgetItem *verItem = table->verticalHeaderItem(table->verticalHeader()->count()-1);
                                    if(verItem)
                                        verItem->setText(QStringLiteral("箱号"));
                                }
                            }

                            if(value_plane_each.contains("putvalue")){
                                table->insertRow(table->rowCount());//新插入一行用于存放投料数值
                                QVariantMap map_boxvalue = (value_plane_each.value("putvalue").toObject().toVariantMap());
                                QMapIterator<QString,QVariant> itor(map_boxvalue);
                                int i_boxvalue = 0;
                                while(itor.hasNext()){
                                    itor.next();
                                    QTableWidgetItem *item_boxvalue = new QTableWidgetItem;
                                    item_boxvalue->setText(itor.value().toString());
                                    int column = 0;
                                    for(int j = 0;j<list_boxnum.count();j++){
                                        if(list_boxnum.at(j) == itor.key()){//查找对应箱号
                                            column = j;
                                            break;
                                        }
                                    }
                                    table->setItem(table->rowCount()-1,column,item_boxvalue);
                                    i_boxvalue++;
                                }
                                //                                                table->verticalHeaderItem(table->rowCount()-1)->setText(QStringLiteral("投喂值"));
                                if(!table->verticalHeaderItem(table->verticalHeader()->count()-1)){
                                    QTableWidgetItem *verItem = new QTableWidgetItem;
                                    verItem->setText(QStringLiteral("投喂值"));
                                    table->setVerticalHeaderItem(table->rowCount()-1,verItem);
                                }else{
                                    QTableWidgetItem *verItem = table->verticalHeaderItem(table->verticalHeader()->count()-1);
                                    if(verItem)
                                        verItem->setText(QStringLiteral("投喂值"));
                                }
                            }

                            if(value_plane_each.contains("weigh")){
                                table->insertRow(table->rowCount());//新插入一行用于存放称量后投料数值
                                QVariantMap map_boxvalue = (value_plane_each.value("putvalue").toObject().toVariantMap());
                                QMapIterator<QString,QVariant> itor(map_boxvalue);
                                int i_boxvalue = 0;
                                while(itor.hasNext()){
                                    itor.next();
                                    QTableWidgetItem *item_boxvalue = new QTableWidgetItem;
                                    item_boxvalue->setText(itor.value().toString());
                                    int column = 0;
                                    for(int j = 0;j<list_boxnum.count();j++){
                                        if(list_boxnum.at(j) == itor.key()){//查找对应箱号
                                            column = j;
                                            break;
                                        }
                                    }
                                    table->setItem(table->rowCount()-1,column,item_boxvalue);
                                    i_boxvalue++;
                                }
                                //                                                table->verticalHeaderItem(table->rowCount()-1)->setText(QStringLiteral("称量值"));
                                if(!table->verticalHeaderItem(table->verticalHeader()->count()-1)){
                                    QTableWidgetItem *verItem = new QTableWidgetItem;
                                    verItem->setText(QStringLiteral("称量值"));
                                    table->setVerticalHeaderItem(table->rowCount()-1,verItem);
                                }else{
                                    QTableWidgetItem *verItem = table->verticalHeaderItem(table->verticalHeader()->count()-1);
                                    if(verItem)
                                        verItem->setText(QStringLiteral("称量值"));
                                }

                                table->insertRow(table->rowCount());
                                table->setSpan(table->rowCount()-1,0,1,24);

                                if(!table->verticalHeaderItem(table->verticalHeader()->count()-1)){
                                    QTableWidgetItem *verItem = new QTableWidgetItem;
                                    verItem->setText(QStringLiteral(""));
                                    table->setVerticalHeaderItem(table->rowCount()-1,verItem);
                                }else{
                                    QTableWidgetItem *verItem = table->verticalHeaderItem(table->verticalHeader()->count()-1);
                                    if(verItem)
                                        verItem->setText(QStringLiteral(""));
                                }

                            }
                        }
                    }
                }
            }
            break;
        }
    }
}


void jsonHelp::updateWidget(QTabWidget *tab)
{
    if(tab){
        tab->clear();
        QDir dir(m_recordDir);
        dir.setFilter(QDir::Files|QDir::NoDotAndDotDot);
        QFileInfo fileinfo;
       if(!dir.entryList().count()){
           return ;
       }else
        //        for(int i = 0;i<4;i++)//search data file from data directory
        {
           foreach(QString str,dir.entryList()){
               fileinfo = QFileInfo(str);
               if(!str.endsWith(".dat"))
                   continue;

               //prepare widget
               QVBoxLayout *layout = new QVBoxLayout;
               layout->setMargin(10);
               layout->setSpacing(6);
               QTabWidget *tabWidgetIn = new QTabWidget(tab);//group
               layout->addWidget(tabWidgetIn);
               QWidget *widgetMain = new QWidget(tab);
               widgetMain->setObjectName(QString("widgetMain_%1").arg(fileinfo.completeBaseName()));
               tabWidgetIn->setObjectName(QString("tabWidgetIn_%1").arg(fileinfo.completeBaseName()));
               widgetMain->setStyleSheet(QString("QWidget#%1{background:transparent;}").arg(widgetMain->objectName()));
               widgetMain->setLayout(layout);

//               if(!mainobj.isEmpty()){
               QJsonObject mainobj;
               readData(dir.absoluteFilePath(str),mainobj);
               if(!mainobj.isEmpty()){
                   QJsonObject obj = mainobj;//parseMain(byte_array,&json_error);
                   QJsonParseError json_error = m_parseerror;

                   QString datatime = "";
                   if(json_error.error == QJsonParseError::NoError){
                       if(obj.contains("datetime"))
                       {
                           QJsonValue version_value = obj.take("datetime");
                           if(version_value.isString())
                           {
                               datatime = version_value.toVariant().toString();
                           }
                       }

                       if(obj.contains("value"))
                       {
                           connect(tabWidgetIn,&QTabWidget::currentChanged,[=](int index){
//                               qDebug()<<"tabBarCurrentChanged:"<<index<<tabWidgetIn->objectName();
                               paraseGroupForTab(obj,tabWidgetIn,index);
                           });
                           connect(tabWidgetIn,&QTabWidget::tabBarClicked,[=](int index){
                               paraseGroupForTab(obj,tabWidgetIn,index);
                           });

//                           foreach(QJsonValue value_group,obj.value("value").toArray())//组
                           for(int index = 0;index<obj.value("value").toArray().size();index++)//组
                           {
                               QJsonValue value_group = obj.value("value").toArray().at(index);
                               QJsonObject obj_group = value_group.toObject();
                               QJsonValue _value;// = obj_group.take("ip");

                               _value = obj_group.take("name");
                               QString group_name = "new";
                               if(_value.isString())
                               {
                                   group_name = _value.toString();
                               }

                               QWidget *widgetGroup = new QWidget(tabWidgetIn);
                               QString title = group_name;
                               QRegExp regexp("(\\d{1,})");
                               if(regexp.indexIn(group_name) != -1){
                                   title = regexp.cap(1);
                               }
//                               int index = tabWidgetIn->count();
//                               tabWidgetIn->insertTab(index,widgetGroup,title);
                               tabWidgetIn->insertTab(index,widgetGroup,title);
                               tabWidgetIn->setTabToolTip(index,group_name);
                           }
                       }
                   }
               }
//               QFileInfo fileinfo(m_recordFile);
               tab->addTab(widgetMain, fileinfo.baseName());
           }
           connect(tab,&QTabWidget::currentChanged,[=](int index){
               QList<QTabWidget *> widgets = tab->widget(index)->findChildren<QTabWidget *>();
               foreach(QTabWidget *tabwidget,widgets){
                   if(QString(tabwidget->metaObject()->className()).contains("QTabWidget")){
                       if(tabwidget->count()){
                           tabwidget->setCurrentIndex(0);
                           qDebug()<<"tab outside change:"<<tabwidget->count()<<tabwidget->objectName();
                       }
                       break;
                   }
               }
           });
           if(tab->count()){
               tab->setCurrentIndex(tab->count()-1);
           }
        }
    }
}

bool jsonHelp::readData(QString filename,QJsonObject &mainobj)
{
    bool ok = false;
    QByteArray data;
    QFile file(filename.isEmpty()?m_recordFile:filename);
    file.fileName();
    if(file.open(QIODevice::ReadOnly)){
        qDebug("fileOpen success.");
        data = file.readAll();
        mainobj = parseMain(data,&m_parseerror);
        this->mainobj = mainobj;
        ok = true;
    }else
        qDebug()<<endl<<endl<<("fileOpen not success.")<<filename;
    return ok;
}

bool jsonHelp::readData(QDateTime datetime)
{
    QString filename = m_recordDir + QString("%1.dat").arg(datetime.toString("yyyyMMdd"));
    return readData(filename);
}
